package com.hq.ims.data.service;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hq.ims.data.config.verification.VdAdd;
import com.hq.ims.data.dao.UserTodoStatisticsMapper;
import com.hq.ims.data.entity.UserTodoStatistics;
import com.hq.ims.data.entityenum.EnumUserTodoType;
import com.hq.ims.data.vo.UserTodoStatisticsDetailMapstruct;
import com.hq.ims.data.vo.UserTodoStatisticsMapstruct;
import com.hq.mybatis.base.BaseService;
import com.hq.mybatis.base.page.RequestPage;
import com.hq.utils.util.ListUtils;
import com.hq.utils.util.StringUtils;
import com.hq.web.utils.SpringBootValidateUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author 蒋柏平
 * @detail 用户端待办统计 服务实现类
 * @since 20241108
 */
@Service
public class BaseUserTodoStatisticsService extends BaseService<UserTodoStatisticsMapper, UserTodoStatistics> {

    @Resource
    private BaseUserTodoStatisticsDetailService baseUserTodoStatisticsDetailService;


    /**
     * 分页
     */
    public List<UserTodoStatisticsMapstruct.UserTodoStatisticsVo> getByPage(
            RequestPage page,
            UserTodoStatisticsMapstruct.PageSearchVo searchVo
    ) {
        //验证
        LambdaQueryChainWrapper<UserTodoStatistics> lq = this.lambdaQuery();
        //排序
        lq.orderByDesc(UserTodoStatistics::getCreateDateTime);
        //查询条件

        //执行分页
        lq.page(page);

        List<UserTodoStatistics> dataList = page.getRecords();
        List<UserTodoStatisticsMapstruct.UserTodoStatisticsVo> voList = UserTodoStatisticsMapstruct.INSTANCE.toUserTodoStatisticsVoList(dataList);
        page.setRecords(voList);
        return voList;
    }

    /**
     * 添加
     */
    @Transactional(rollbackFor = Exception.class)
    public UserTodoStatistics addData(UserTodoStatisticsMapstruct.SaveVo vo) {
        //验证
        SpringBootValidateUtils.validate(vo, VdAdd.class);

        //账值新的对象
        UserTodoStatistics entity = new UserTodoStatistics();
        entity.setUserTodoType(vo.getUserTodoType());
        entity.setUserTodoTypeCount(vo.getUserTodoTypeCount());
        entity.setUserId(vo.getUserId());
        entity.setCompanyId(vo.getCompanyId());

        entity.insert();

        //插件详情
        if (StringUtils.isEmpty(vo.getTableId())) {
            UserTodoStatisticsDetailMapstruct.SaveVo detailSaveVo = new UserTodoStatisticsDetailMapstruct.SaveVo();
            detailSaveVo.setUserTodoStatisticsId(entity.getUserTodoStatisticsId());
            detailSaveVo.setUserTodoType(entity.getUserTodoType());
            detailSaveVo.setUserId(entity.getUserId());
            detailSaveVo.setCompanyId(entity.getCompanyId());
            detailSaveVo.setTableId(vo.getTableId());
            baseUserTodoStatisticsDetailService.addData(detailSaveVo);
        }

        return entity;
    }

    /**
     * 按类型累加数量,允许为负数
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCountByUserTodoType(
            @NotNull EnumUserTodoType userTodoType,
            @NotNull Integer addCount,
            @NotNull String tableId,
            @NotNull String userId,
            @NotNull String companyId
    ) {
        UserTodoStatistics userTodoStatistics = this.getByUserTodoType(userTodoType, userId, companyId);
        if (userTodoStatistics == null) {
            UserTodoStatisticsMapstruct.SaveVo saveVo = new UserTodoStatisticsMapstruct.SaveVo();
            saveVo.setUserTodoType(userTodoType);
            saveVo.setUserTodoTypeCount(addCount < 0 ? 0 : addCount);
            saveVo.setCompanyId(companyId);
            saveVo.setUserId(userId);
            saveVo.setTableId(tableId);
            userTodoStatistics = this.addData(saveVo);
        } else {
            int finalCount = userTodoStatistics.getUserTodoTypeCount() + addCount;
            userTodoStatistics.setUserTodoTypeCount(finalCount < 0 ? 0 : finalCount);
            userTodoStatistics.updateById();
        }

        if (StringUtils.isNotEmpty(tableId)) {
            if (addCount > 0) {
                UserTodoStatisticsDetailMapstruct.SaveVo saveVo = new UserTodoStatisticsDetailMapstruct.SaveVo();
                saveVo.setUserTodoStatisticsId(userTodoStatistics.getUserTodoStatisticsId());
                saveVo.setUserTodoType(userTodoStatistics.getUserTodoType());
                saveVo.setUserId(userId);
                saveVo.setCompanyId(companyId);
                saveVo.setTableId(tableId);
                baseUserTodoStatisticsDetailService.addData(saveVo);
            } else if (addCount < 0) {
                baseUserTodoStatisticsDetailService.delByUserTodoTypeAndTableId(userTodoType, tableId,userId,companyId);
            }
        }
    }

    /**
     * 根据平台待办类型获取统计
     *
     * @param userType 平台待办类型
     */
    public UserTodoStatistics getByUserTodoType(EnumUserTodoType userType, String userId, String companyId) {
        List<UserTodoStatistics> list = this.lambdaQuery()
                .eq(UserTodoStatistics::getUserTodoType, userType)
                .eq(UserTodoStatistics::getUserId, userId)
                .eq(UserTodoStatistics::getCompanyId, companyId)
                .list();
        if (ListUtils.isExistsEle(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void delData(String userTodoStatisticsId) {
        UserTodoStatistics data = this.getById(userTodoStatisticsId);
        if (data == null) {
            return;
        }
        data.deleteById();
    }

    /**
     * 获取原始数据详情
     */
    public UserTodoStatisticsMapstruct.UserTodoStatisticsVo getDetailVo(String userTodoStatisticsId) {
        UserTodoStatistics entity = this.getById(userTodoStatisticsId);
        UserTodoStatisticsMapstruct.UserTodoStatisticsVo vo = UserTodoStatisticsMapstruct.INSTANCE.toUserTodoStatisticsVo(entity);
        return vo;
    }

    /**
     * 清除待办
     *
     * @param clearTodo 清除待办
     */
    public void clearTodo(UserTodoStatisticsMapstruct.ClearTodo clearTodo) {
        SpringBootValidateUtils.validate(clearTodo);

        List<UserTodoStatistics> list = this.lambdaQuery()
                .eq(UserTodoStatistics::getUserTodoType, clearTodo.getUserTodoType())
                .eq(UserTodoStatistics::getCompanyId, clearTodo.getCompanyId())
                .eq(StringUtils.isNotEmpty(clearTodo.getUserId()),UserTodoStatistics::getUserId, clearTodo.getUserId())
                .list();

        for (UserTodoStatistics userTodoStatistics : list) {
            int diff = userTodoStatistics.getUserTodoTypeCount() - clearTodo.getClearCount();
            diff = diff > 0 ? diff : 0;
            this.lambdaUpdate().eq(UserTodoStatistics::getCompanyId, clearTodo.getCompanyId())
                    .eq(UserTodoStatistics::getUserTodoType, clearTodo.getUserTodoType())
                    .eq(UserTodoStatistics::getCompanyId, clearTodo.getCompanyId())
                    .eq(StringUtils.isNotEmpty(clearTodo.getUserId()),UserTodoStatistics::getUserId, clearTodo.getUserId())
                    .set(UserTodoStatistics::getUserTodoTypeCount, diff)
                    .update();
        }
    }

    /**
     * 根据公司ID和用户ID获取待办
     *
     * @param companyId 公司ID
     * @param userId    用户ID
     */
    public List<UserTodoStatisticsMapstruct.UserTodoStatisticsVo> getByCompanyIdAndUserId(
            String companyId,
            String userId
    ) {
        List<UserTodoStatistics> list = this.lambdaQuery()
                .eq(UserTodoStatistics::getCompanyId, companyId)
                .eq(UserTodoStatistics::getUserId, userId)
                .orderByAsc(UserTodoStatistics::getUserTodoType)
                .list();
        List<UserTodoStatisticsMapstruct.UserTodoStatisticsVo> voList = UserTodoStatisticsMapstruct.INSTANCE.toUserTodoStatisticsVoList(list);
        return voList;
    }
}